#include "Timer.hpp"

#include <iostream>

__int64 Timer::_GetCounts()
{
	return al_get_timer_count(_allegro_timer.get());
}

void Timer::_CreateFont()
{
	_font.reset(al_load_ttf_font("../fonts/arial.ttf", _font_size, 0), [](ALLEGRO_FONT* p){al_destroy_font(p);});
	if(!_font)
		std::cerr << "Failed to create timer font.\n";
}

Timer::Timer()
	: _font_size(12),
	  _display_fps("Frames Per Second: %f"),
	  _display_mspf("Milliseconds Per Frame: %f"),
	  _fps(0.0f),
	  _mspf(0.0f),
	  _paused(false),
	  _resumed(false),
	  _counts_this_frame(0),
	  _counts_last_frame(0),
	  _seconds_per_count(0.0000001),
	  _allegro_timer(al_create_timer(_seconds_per_count), [](ALLEGRO_TIMER* p){al_destroy_timer(p);}),
	  _dt(0.0f)
{
	al_start_timer(_allegro_timer.get());

	_CreateFont();
}

float Timer::GetDT() const
{
	return _dt;
}

void Timer::Pause()
{
	_paused = true;
	std::cout << "Pausing..." << std::endl;
}

void Timer::Resume()
{
	_paused = false;
	_resumed = true;
	std::cout << "Resuming..." << std::endl;
}

bool Timer::IsPaused() const
{
	return _paused;
}

void Timer::Update()
{
	static float time_elapsed(0.0f);
	static int number_of_frames(0);

	if(_resumed)
	{
		_counts_this_frame = _GetCounts();
		_counts_last_frame = _counts_this_frame;
		_resumed = false;
	}
	else
	{
		_counts_last_frame = _counts_this_frame;
		_counts_this_frame = _GetCounts();
	}

	_dt = (_counts_this_frame - _counts_last_frame) * _seconds_per_count;
	time_elapsed += _dt;

	++number_of_frames;

	bool at_least_one_second_elapsed(1.0f <= time_elapsed);
	if(at_least_one_second_elapsed)
	{
		time_elapsed = 0;

		_fps = static_cast<float>(number_of_frames);
		number_of_frames = 0;

		_mspf = 1000.0f / _fps;
	}
}

void Timer::DrawTimerText() const
{
	// Allegro won't create newlines while drawing text. We must make two calls to
	// achieve the effect of newline.
	al_draw_textf(_font.get(), al_map_rgb(0, 0, 0), 5, 5, 0, _display_fps.c_str(), _fps);
	al_draw_textf(_font.get(), al_map_rgb(0, 0, 0), 5, _font_size+5, 0, _display_mspf.c_str(), _mspf);
}